package cn.fenqing168.bio.groupchat;

import lombok.SneakyThrows;

import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author fenqing
 */
public class GroupchatClient {

    /**
     * 通道
     */
    private SocketChannel socketChannel;

    /**
     * 选择器
     */
    private Selector selector;

    /**
     * 用户名
     */
    private String username;

    /**
     * 构造器
     */
    @SneakyThrows
    public GroupchatClient(){
        //打开一个选择器
        selector = Selector.open();
        //打开一个通道
        Scanner input = new Scanner(System.in);
        System.out.println("请输入服务器ip：");
        String ip = input.next();
        System.out.println("请输入服务器端口：");
        int port = input.nextInt();
        System.out.println("请输入昵称：");
        username = input.next();
        socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
        //设置非堵塞
        socketChannel.configureBlocking(false);
        //注册到通道
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    /**
     * 发送消息
     * @param msg 消息
     */
    @SneakyThrows
    public void sendInfo(String msg){
        String text = username + " 说: " + msg;
        socketChannel.write(ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 读取消息
     */
    @SneakyThrows
    public void readInfo(){
        //是否有可读取
        int select = selector.select();
        if(select > 0){
            //获取全部可读取
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SocketChannel socketChannel = (SocketChannel) iterator.next().channel();
                //读取数据
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                while (socketChannel.read(byteBuffer) > 0){
                    baos.write(byteBuffer.array(), 0, byteBuffer.position());
                    byteBuffer.clear();
                }
                System.out.println(baos);
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) {
        GroupchatClient groupchatClient = new GroupchatClient();
        new Thread(() -> {
            while (true){
                groupchatClient.readInfo();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner input = new Scanner(System.in);
        while (true){
            groupchatClient.sendInfo(input.next());
        }

    }

}
